<template>
	<view class="content">
		<view class="header">
			<view class="headtitle">
				仿微信({{length}})
			</view>
			<view class="">
				<img src="../../static/search.png" class="search" alt="" srcset="">
				<img src="../../static/add.png" class="add" @click="add" alt="" srcset="">
			</view>
		</view>
		<view class="listbody">
			<view class="newlist" v-for="(item,index) in list" @longpress="long(item,index)" @click="tzchat(item)"
				:key="index">
				<view class="avator">
					<img src="../../static/avator.png" alt="">
					<view v-if="item.sfyd == false">{{item.data.length}}</view>
				</view>
				<view class="newright">
					<view class="newtop">
						<view class="avaname">
							{{item.name}}
						</view>
						<view class="time">
							{{item.data[item.data.length-1].create_time}}
						</view>
					</view>
					<view class="news" v-if="item.data.length !==0">
						{{item.data[item.data.length-1].from_name}}: {{item.data[item.data.length-1].data}}
					</view>
				</view>

			</view>
		</view>

		<view class="popup" v-show="extendshow" @click="chanfe">

		</view>
		<view class="popup" v-show="extendshow3" @click="chanfe1">

		</view>
		<view class="poptanchuang" v-show="extendshow1" :style="'left:'+this.x+'px;top:'+this.y+'px'">
			<view class="poplist" @click="zdchat()">
				{{zdtitle}}
			</view>
			<view class="poplist" @click="shanchu()">
				删除该聊天
			</view>
		</view>
		<view class="poptanchuang1" v-show="extendshow2">
			<view class="poplist1">
				<img src="../../static/fqql.png"
					style="width:20px;height: 22px;margin-right: 10px;vertical-align: middle;" alt="" /> 发起群聊
			</view>
			<view class="poplist1">
				<img src="../../static/tjhy.png"
					style="width:27px;height: 22px;margin-right: 3px;vertical-align: middle;" alt="" />
				添加好友
			</view>
			<view class="poplist1">
				<img src="../../static/sfk.png"
					style="width:20px;height: 22px;margin-right: 10px;vertical-align: middle;" alt="" />
				收付款
			</view>
			<view class="poplist1">
				<img src="../../static/bzyfk.png"
					style="width:20px;height: 22px;margin-right: 10px;vertical-align: middle;" alt="" />
				帮助与反馈
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				title: 'Hello',
				newdata: [],
				webSocketTask: null,
				proindex: 0,
				extendshow: false,
				extendshow1: false,
				extendshow2: false,
				extendshow3: false,
				x: "",
				y: "",
				popstyle: {

				},
				zdtitle: "",
				xzid: "",
				list: [],
				user: {},
				length: 0
			}
		},
		computed: {

		},
		onLoad() {
			// this.user = JSON.parse(uni.getStorageSync("user"))
			// console.log(JSON.parse(uni.getStorageSync("user")));

			// this.socket()
			// this.getdata()
		},
		onShow() {
	this.user = JSON.parse(uni.getStorageSync("user"))
			console.log(JSON.parse(uni.getStorageSync("user")));

			this.socket()
			this.getdata()
	

		},
		methods: {
			socket() {
				// uni.showTabBarRedDot({ //显示红点 
				//     index: 0 //tabbar下标
				// })
				this.webSocketTask = uni.connectSocket({
					url: "ws://wechat.dishait.cn/ws" + "?token=" + window.localStorage.getItem("token"),
					header: {
						'content-type': 'application/json'
					},
					success(res) {
						console.log("websocket连接成功", res);
					}
				})
				this.webSocketTask.onOpen(res => {
					console.log(res, "open");
				})
				uni.onSocketError((res) => {
					console.info("监听WebSocket错误" + res)
				});
				this.webSocketTask.onMessage(res => {
					console.log(res, "res");

					this.newdata.push(JSON.parse(res.data))

					console.log(this.newdata, "newdata");
					this.newdata.forEach(el => {

						console.log(typeof(1711453549430));
						console.log(typeof(el.data.create_time));
						console.log(typeof(el.data.create_time));
						typeof(el.data.create_time)
						console.log(this.formatSendTime(1711453549430));
						console.log(this.formatSendTime(el.data.create_time));

						// el.data.create_time= this.formatSendTime(el.data.create_time)
					})
					let arr = [];
					this.newdata.forEach(el => {
						let flag = arr.find(item1 =>

							item1.name === el.data.from_name)
						console.log(flag, 'flag');
						if (!flag) {
							arr.push({
								name: el.data.from_name,
								sfyd: false,
								data: [el.data]
							})
						} else {
							flag.data.push(el.data)
						}
					})


					console.log(arr, 'arr');
					arr.forEach(el => {
						el.id = el.data[0].from_id
					})
					// let datt=JSON.parse(uni.getStorageSync(`user_${this.user.id}`));
					// console.log(datt,'datt');
					// arr.forEach(el=>{
					// 	datt.push(el)
					// })
					uni.setStorageSync(`user_${this.user.id}`, JSON.stringify(arr))
					this.getdata()
				})
			},
			getdata() {
				if (uni.getStorageSync(`user_${this.user.id}`)) {
					this.list = JSON.parse(uni.getStorageSync(`user_${this.user.id}`))
					let length = 0;
					this.list.forEach(el => {
						if (el.sfyd == false) {
							length += el.data.length
						}

						el.data.forEach(el2 => {
							console.log(typeof(el2.create_time), "123");
							if (typeof(el2.id) == 'number') {
								el2.create_time = this.formatSendTime(el2.id)

							}
							console.log(el2.create_time);
						})
					})
					console.log(length);
					this.length = length
					if(this.length>0){
					uni.setTabBarBadge({ //显示红点
						index: 0,
						text: String(length)
					})						
					}

				}

			},
			formatSendTime(sendTime) {
				const now = new Date()
				const sendDate = new Date(sendTime)

				console.log(now, '11111', sendDate, 'shijian')
				// 计算时间差（以毫秒为单位）
				const timeDiff = now - sendDate
				// console.log(timeDiff, '时间差')
				const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate())
				const startOfTargetDate = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate())

				// 一天内的毫秒数
				const oneDay = 24 * 60 * 60 * 1000

				// 如果发送时间在当前时间之前
				if (timeDiff < 0) {
					return 'Invalid time' // 或者其他错误处理
				}
				// 发生在同一天
				if (startOfToday.getTime() === startOfTargetDate.getTime()) {
					return this.formatTime(sendDate)
				}
				// 如果发送时间在一天内
				if (timeDiff < oneDay) {
					return '昨天 ' + this.formatTime(sendDate)
				}

				// 如果发送时间在二天至七天内
				if (timeDiff < 7 * oneDay) {
					const weekday = this.getWeekday(sendDate)
					return weekday + ' ' + this.formatTime(sendDate)
				}

				// 如果发送时间超过七天
				return (
					sendDate.toLocaleDateString('zh-CN', {
						year: 'numeric',
						month: '2-digit',
						day: '2-digit'
					}) +
					' ' +
					this.formatTime(sendDate)
				)
			},
			formatTime(date) {
				console.log(date, 'date');
				// 格式化时间为“时:分”
				const hours = date.getHours().toString().padStart(2, '0')
				const minutes = date.getMinutes().toString().padStart(2, '0')
				return hours + ':' + minutes
			},
			getWeekday(date) {
				// 获取星期几的中文表示
				const weekdays = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
				return weekdays[date.getDay()]
			},
			tzchat(e) {
				console.log(this.list);
				console.log(e);
				
				let data = JSON.stringify(e)
				let arr={};
				if(uni.getStorageSync(`chatdetail${this.user.id}_user${e.id}`)){
					arr=JSON.parse(uni.getStorageSync(`chatdetail${this.user.id}_user${e.id}`));
					
				}
				uni.setStorageSync(`chatdetail${this.user.id}_user${e.id}`, JSON.stringify(e))
				this.list.forEach((el, index) => {
					if (el.id == e.id) {
						el.sfyd = true
					}
				})
				
				uni.setStorageSync(`user_${this.user.id}`, JSON.stringify(this.list))

				uni.navigateTo({
					url: `/pages/chat/chat?params=${data}`
				})
			},
			add() {
				this.extendshow2 = true;
				this.extendshow3 = true
			},
			chanfe() {
				this.extendshow1 = false
				this.extendshow = false
			},
			chanfe1() {
				this.extendshow2 = false;
				this.extendshow3 = false

			},
			long(item, index) {
				// #ifdef MP
				console.log(e.changedTouches)
				// #endif
				// #ifdef H5
				console.log(event.changedTouches)
				console.log(index)
				this.proindex = index
				this.xzid = item.id
				let x = 0;
				let y = 0;
				if (Array.isArray(event.changedTouches) || (event.changedTouches.length > 0)) {
					x = event.changedTouches[0].pageX;
					y = event.changedTouches[0].pageY;
					console.log(x, y)
					this.extendshow = true
					this.extendshow1 = true
					this.x = x;
					this.y = y


				}
				// #endif
				if (item.iszd == true) {
					this.zdtitle = "取消置顶"
				} else {
					this.zdtitle = "置顶聊天"

				}

			},
			shanchu() {
				console.log(this.proindex);
				this.list.splice(this.proindex, 1)

				uni.setStorageSync(`user_${this.user.id}`, JSON.stringify(this.list))
				console.log(this.list);
				this.extendshow = false;
				this.extendshow1 = false
			},
			zdchat() {
				if (this.zdtitle == '取消置顶') {
					this.list.forEach(el => {
						if (el.id == this.xzid) {
							el.iszd = false
						}
					})
				} else {
					this.list.forEach(el => {
						if (el.id == this.xzid) {
							el.iszd = true
						}
					})

				}
				this.extendshow = false;
				this.extendshow1 = false
				console.log(this.list)
			},

		}
	}
</script>

<style>
	.content {
		width: 100%;
		height: 100%;
	}

	.poplist {
		width: 100%;
		height: 103rpx;
		background: #fff;
		text-align: center;
		line-height: 103rpx;
		color: #000;
	}

	.poplist1 {
		width: 100%;
		height: 103rpx;
		background: #000;
		text-align: left;
		padding-left: 20rpx;
		box-sizing: border-box;
		line-height: 103rpx;
		color: #fff;
	}

	.popup {
		width: 260rpx;
		height: 216rpx;
		position: fixed;
		border: 1px solid #dee2e6;
	}

	.header {
		width: 100%;
		height: 90rpx;
		background: #f8f9fa;
		display: flex;
		box-sizing: border-box;
		padding: 0px 20rpx;
		justify-content: space-between;
		align-items: center;

	}

	.search {
		width: 40rpx;
		margin-right: 30rpx;
		height: 42rpx;
		/* 		height: 42rpx; */
	}

	.add {
		width: 40rpx;
		height: 42rpx;
	}

	.headtitle {
		font-size: 36rpx;
	}

	.listbody {
		width: 100%;
		height: calc(100% - 90rpx);
		overflow: auto;
		background: #fff;


	}

	.newlist {
		width: 100%;
		height: auto;

		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.avator {
		width: 100rpx;
		height: 100rpx;
		position: relative;

	}

	.avator view {
		position: absolute;
		right: 0px;
		top: 0px;
		background: red;
		color: #fff;
		width: 40rpx;
		height: 40rpx;
		text-align: center;
		border-radius: 50%;
	}

	.avator img {
		width: 100%;
		height: 100%;
	}

	.newright {
		width: calc(100% - 100rpx);
		height: auto;
		padding: 32rpx 20rpx 32rpx 20rpx;
		box-sizing: border-box;
		border-bottom: 1px solid #E9E8E5;
	}

	.newtop {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.avaname {
		font-size: 36rpx;
		width: 220rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.time {
		font-size: 28rpx;
		color: #A9A5A0;
	}

	.news {
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
		font-size: 28rpx;
		color: #A9A5A0;
	}

	.popup {
		position: fixed;
		top: 0px;
		left: 0px;
		width: 100%;
		height: 100%;
	}

	.poptanchuang {
		width: 128px;
		height: 106px;
		border-width: 1px;
		border-style: solid;
		border-color: #dee2e6;
		position: fixed;
	}

	.poptanchuang1 {
		width: 128px;
		height: auto;
		background: #000;
		right: 0px;
		top: 80px;
		position: fixed;
	}
</style>